package com.string.actortv.util;

import android.util.Log;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.string.actortv.dto.MovieInfo;
import com.string.actortv.dto.MovieList;
import com.string.actortv.dto.MovieTypeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.string.actortv.util.CacheHelper.CACHE;

/**
 * 梵菲电影网
 */
public class FanFeiUtil {

    private static final String BASE_URL = "https://www.fanfeifan.com";

    /**
     * https://www.fanfeifan.com/show/1--------2---.html
     */
    private static final String BASE_PAGE_URL = "https://www.fanfeifan.com/show/";

    private static final String BASE_SEARCH_URL = "https://www.fanfeifan.com/search/";

    private static String getBaseTypeUrl(String action) {
        return "https://www.fanfeifan.com/show/" + action + "-----------.html";
    }

    public interface MovieTypeCallBack {
        void execute(List<MovieTypeList> movieTypeList);
    }

    /**
     * @param action
     * @param callBack
     */
    public static void getMovieTypeAsync(String action, MovieTypeCallBack callBack) {
        MyHttpUtil.getAsync(getBaseTypeUrl(action), html -> {
            Document document = Jsoup.parse(html);
            List<MovieTypeList> movieTypeLists = new ArrayList<>();
            Elements liElements = document.getElementsByClass("myui-screen__list").get(0)
                    .getElementsByTag("li");
            for (Element li : liElements) {
                if (!li.getElementsByTag("a").get(0).text().equals("类型")) {
                    MovieTypeList movieTypeList = new MovieTypeList(li.getElementsByTag("a").get(0).text(), li.getElementsByTag("a").get(0).attr("href"));
                    movieTypeLists.add(movieTypeList);
                }
            }
            callBack.execute(movieTypeLists);
        }, null);
    }

    public interface MovieUrlCallBack {
        void execute(String playUrl);
    }

    public static void getMovieUrlAsync(String pageUrl, MovieUrlCallBack callBack) {
        MyHttpUtil.getAsync(pageUrl, html -> {
            Document document = Jsoup.parse(html);
            Element cmsPlay = document.getElementsByClass("embed-responsive").get(0);
            String scriptStr = cmsPlay.getElementsByTag("script").get(0).html();
            String jsonStr = scriptStr.substring(scriptStr.indexOf("=") + 1)
                    .replace("\\", "").replace(";", "");
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String playUrl = jsonObject.getString("url");
            callBack.execute(playUrl);
        }, null);
    }

    public interface MovieListCallBack {
        void execute(List<MovieList> movieList);
    }

    public static void getMovieListAsync(int pageNo, String searchStr,
                                         String type, String action,
                                         MovieListCallBack movieListCallBack) {
        StringBuilder pageUrl;
        if (StrUtil.isEmpty(searchStr)) {
            if (StrUtil.isEmpty(type)) {
                pageUrl = new StringBuilder(BASE_PAGE_URL + action + "--------" + pageNo + "---.html");
            } else {
                pageUrl = new StringBuilder(BASE_URL + type);
                //替换分页位，pageNo + "---.html"
                //https://www.fanfeifan.com/show/2--------2---.html
                //https://www.fanfeifan.com/show/2-----------.html
                pageUrl.insert(pageUrl.indexOf("---.html"), pageNo);
            }
            if (CACHE.containsKey(pageUrl.toString())
                    && CACHE.get(pageUrl.toString()) != null) {
                getList(pageUrl.toString(), searchStr, CACHE.get(pageUrl.toString()).toString(), movieListCallBack);
            } else {
                MyHttpUtil.getAsync(pageUrl.toString(), result -> getList(pageUrl.toString(), searchStr, result, movieListCallBack), null);
            }
        } else {
            //https://www.fanfeifan.com/search/111----------1---.html
            pageUrl = new StringBuilder(BASE_SEARCH_URL + URLEncoder.encode(searchStr) + "----------" + pageNo + "---.html");
            if (CACHE.containsKey(pageUrl.toString())
                    && CACHE.get(pageUrl.toString()) != null) {
                getList(pageUrl.toString(), searchStr, CACHE.get(pageUrl.toString()).toString(), movieListCallBack);
            } else {
                MyHttpUtil.getAsync(pageUrl.toString(), result -> getList(pageUrl.toString(), searchStr, result, movieListCallBack), null);
            }
        }
    }

    private static void getList(String pageUrl, String searchStr,
                                String html, MovieListCallBack movieListCallBack) {
        if ("".equals(html)) {
            Log.d("FanFeiGetList", html);
            movieListCallBack.execute(null);
            return;
        }
        CACHE.put(pageUrl, html);
        Document document = Jsoup.parse(html);
        List<MovieList> movieList = new ArrayList<>();
        //获取当前电影列表
        Elements movieElements;
        if (StrUtil.isNotEmpty(searchStr)) {
            Element content = document
                    .getElementById("searchList");
            movieElements = content
                    .getElementsByTag("li");
        } else {
            Element content = document
                    .getElementsByClass("myui-vodlist").get(0);
            movieElements = content
                    .getElementsByTag("li");
        }
        if (movieElements != null) {
            for (Element movieElement : movieElements) {
                Elements elements = movieElement.getElementsByTag("div").get(0).getElementsByTag("a");
                if (!elements.isEmpty()) {
                    String name = elements.get(0).attr("title");
                    String img = elements.get(0).attr("data-original");
                    String url = BASE_URL + elements.get(0).attr("href");
                    if (img.startsWith("//")) {
                        img = "https:" + img;
                    } else if (img.startsWith("/")) {
                        img = BASE_URL + img;
                    }
                    movieList.add(new MovieList(name, url, img));
                }
            }
        }
        movieListCallBack.execute(movieList);
    }

    public interface MovieInfoCallBack {
        void execute(MovieInfo movieInfo);
    }

    public static void getMovieInfoAsync(String href, String name, MovieInfoCallBack movieInfoCallBack) {
        //获取电影集数列表
        if (CACHE.containsKey(href)
                && CACHE.get(href) != null) {

            getInfo(name, CACHE.get(href).toString(), movieInfoCallBack);
        } else {
            MyHttpUtil.getAsync(href, movieHtml -> {
                if ("".equals(movieHtml)) {
                    movieInfoCallBack.execute(null);
                    return;
                }
                CACHE.put(href, movieHtml);

                getInfo(name, movieHtml, movieInfoCallBack);
            }, null);
        }
    }

    private static void getInfo(String name, String movieHtml, MovieInfoCallBack movieInfoCallBack) {
        Document document = Jsoup.parse(movieHtml);
        //视频图片
        Elements imgElements = document.getElementsByClass("picture");
        String img = imgElements.get(0).getElementsByTag("img").get(0).attr("data-original");
        //视频介绍
        Element descElement = document.getElementById("desc");
        String desc = descElement.text();
        Elements listElements = document
                .getElementById("playlist1")
                .getElementsByTag("li");
        List<MovieInfo.SeasonList> seasonList = new ArrayList<>();
        if (listElements != null && !listElements.isEmpty()) {
            for (Element seasonElement : listElements) {
                String seasonName = seasonElement.text();
                String url = BASE_URL + seasonElement.getElementsByTag("a").get(0).attr("href");

                seasonList.add(new MovieInfo.SeasonList(seasonName, url));
            }
        }
        movieInfoCallBack.execute(new MovieInfo(name, img, desc, seasonList));
    }

}
